//
//  AppDelegate.m
//  JiuLe
//
//  Created by xcq on 15/10/31.
//  Copyright © 2015年 Fine. All rights reserved.
//
#import "Common.h"
#import "AppDelegate.h"
#import "JLClockModel.h"
#import "JLCallMeModel.h"
#import "JlUserManager.h"
#import <GTSDK/GeTuiSdk.h>
#import "BaseNavController.h"
#import <IQKeyboardManager.h>
#import "MallViewController.h"
#import "CYLTabBarController.h"
#import "LoginViewController.h"
#import "MyZoneViewController.h"
#import "UIColor+RGBConverHex.h"
#import "ServiceViewController.h"
#import "MessageViewController.h"
#import "HomePageViewController.h"
#import "ActivateViewController.h"
#import "IntroGuideViewController.h"
#import "JLContentViewController.h"


#import "SideMenuContentViewController.h"

/// 个推开发者网站中申请App时注册的AppId、AppKey、AppSecret
#define kGtAppId           @"63GHvHb4Qr8cIluoXJF797"
#define kGtAppKey          @"w5FhVpAEBcAewXzpmEVHHA"
#define kGtAppSecret       @"gOQwA9qTBU9IiSaoby34g2"
//测试用
//#define kGtAppId           @"W7K1ka9ZDCACheqDMBRHwA"
//#define kGtAppKey          @"446tiTZkUq7658eiGoibd1"
//#define kGtAppSecret       @"446tiTZkUq7658eiGoibd1"

static BOOL isBackGround = NO;

@interface AppDelegate () <GeTuiSdkDelegate,UIAlertViewDelegate>
{
    
}
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [self.window makeKeyAndVisible];
//    [self initPlist];
    [MAMapServices sharedServices].apiKey = MAPKEY;
    [[IQKeyboardManager sharedManager] setEnable:YES];
    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:NO];
//    [self updateWatchData];
    [AppDelegate chooseRootViewController];
    [self initGePush:launchOptions];
    
    NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (userInfo) {
        [self receiveNotificationByLaunchingOptions:userInfo];
    }
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    return YES;
}

- (void)networkStateChange
{
    [self checkNetworkState];
}

- (void)checkNetworkState
 {
         // 1.检测wifi状态
         Reachability *wifi = [Reachability reachabilityForLocalWiFi];
    
         // 2.检测手机是否能上网络(WIFI\3G\2.5G)
         Reachability *conn = [Reachability reachabilityForInternetConnection];
    
         // 3.判断网络状态
        if ([wifi currentReachabilityStatus] != NotReachable) { // 有wifi
                NSLog(@"有wifi");
            [[NSUserDefaults standardUserDefaults]setObject:@"wifi" forKey:JiuLeNetBility];
        } else if ([conn currentReachabilityStatus] != NotReachable) { // 没有使用wifi, 使用手机自带网络进行上网
                NSLog(@"使用手机自带网络进行上网");
            [[NSUserDefaults standardUserDefaults]setObject:@"3g" forKey:JiuLeNetBility];
        } else { // 没有网络
                NSLog(@"没有网络");
            [[NSUserDefaults standardUserDefaults]setObject:@"none" forKey:JiuLeNetBility];
        }
}

- (void)initGePush:(NSDictionary *)launchOptions {
    
    // 通过个推平台分配的appId、 appKey 、appSecret 启动SDK，注：该方法需要在主线程中调用
    [GeTuiSdk startSdkWithAppId:kGtAppId
                         appKey:kGtAppKey
                      appSecret:kGtAppSecret
                       delegate:self];
    
    // 注册APNS
    [self registerUserNotification];
}

/*
 "clock": "",
 "remind_type": "",
 "type": "1",
 "is_set": ""
 */
inline NSDictionary * returnClockeModel(JLClockModel *model) {
    NSDictionary *dic = @{@"clock":model.clock,
                          @"remind_type":model.remind_type,
                          @"type":model.type,
                          @"is_set":model.is_set};
    return dic;
}

- (void)updateWatchData {
    if ([[NSUserDefaults standardUserDefaults] objectForKey:UserSetWatchAlarmData] == nil) {
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:UserSetWatchAlarmData];
        [[NSUserDefaults standardUserDefaults]setBool:NO forKey:UserSetWatchValveData];
    } else {
        BOOL bol = [[[NSUserDefaults standardUserDefaults] objectForKey:UserSetWatchAlarmData] boolValue];
        BOOL bol1 = [[[NSUserDefaults standardUserDefaults] objectForKey:UserSetWatchValveData] boolValue];
         if (bol) {
            //请求
            NSString *type1 = [[NSUserDefaults standardUserDefaults] objectForKey:UserDataAlarmChangeOne];
            NSString *type2 = [[NSUserDefaults standardUserDefaults] objectForKey:UserDataAlarmChangeTwo];
            NSString *type3 = [[NSUserDefaults standardUserDefaults] objectForKey:UserDataAlarmChangeThree];
            NSMutableArray *clockSet = [NSMutableArray new];
            if (type1 !=nil && ![type1 isEqualToString:@""]) {
                JLClockModel *model = [NSUserDefaults objectUserForKey:UserDataAlarmArraysOne];
                [clockSet addObject:returnClockeModel(model)];
            }
            if (type2 != nil && ![type2 isEqualToString:@""]) {
                JLClockModel *model = [NSUserDefaults objectUserForKey:UserDataAlarmArraysTwo];
                
                [clockSet addObject:returnClockeModel(model)];
            }
            if (type3 != nil && ![type3 isEqualToString:@""]) {
                JLClockModel *model = [NSUserDefaults objectUserForKey:UserDataAlarmArraysThree];
                [clockSet addObject:returnClockeModel(model)];
            }
            JLLog(@"clockSet:%@",clockSet);
            [SVProgressHUD showSuccessWithStatus:[NSString stringWithFormat:@"%@",clockSet]];
            [InterfaceNetManager SetClockSetting:^(BOOL isSucceed,
                                                   NSString *message,
                                                   id data,
                                                   NSError *error) {
                if (isSucceed) {
                    JLLog(@"闹钟数据上传成功");
                    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:UserSetWatchAlarmData];
                } else {
                    JLLog(@"闹钟数据上传失败");
                }
             } andParameter:@{@"username":[JlUserManager shareInstance].userInfo.userid,
                              @"clockset":clockSet}];
            
        }
        if (bol1) {
            NSString *seleteType = [[NSUserDefaults standardUserDefaults] objectForKey:UserHealthSelete];
            NSMutableDictionary *data = [Common loadPlist:@"HealthThresholds"];
            NSMutableDictionary *setData = [NSMutableDictionary dictionaryWithDictionary:[data objectForKey:@"set"]];
            NSMutableArray *arr = nil;
            NSInteger type = 0;
            if ([seleteType isEqualToString:@"房颤"]) {
                type = 1;
                arr = [setData objectForKey:@"fc"];
            } else if ([seleteType isEqualToString:@"鼾症"]) {
                type = 2;
                arr = [setData objectForKey:@"hz"];
            } else if ([seleteType isEqualToString:@"亚健康"]) {
                type = 3;
                arr = [setData objectForKey:@"yjk"];
            } else {
                type = 4;
                arr = [setData objectForKey:@"zdy"];
            }
            if (arr.count == 0) {
                return;
            }
            //低心率，高心率，血氧
            NSDictionary *param = @{@"userid":[JlUserManager shareInstance].userInfo.userid,
                                    @"high_hr":[arr objectAtIndex:1],
                                    @"low_hr":[arr objectAtIndex:0],
                                    @"spo2":[arr lastObject],
                                    @"type":@(type),
                                    @"is_set":@(1)};
            [InterfaceNetManager SetHealthSetting:^(BOOL isSucceed,
                                                    NSString *message,
                                                    id data,
                                                    NSError *error) {
                if (isSucceed) {
                    JLLog(@"健康阀值上传成功");
                    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:UserSetWatchValveData];
                } else {
                    JLLog(@"健康阀值上传失败");
                }
            } andParameter:param];
        }
    }
}

- (void)initPlist {
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:JiuLeOfflineMode];
    
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:JiuLeIsConnection];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"HealthThresholds.plist"]; NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if (![fileManager fileExistsAtPath: path])
    {
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:@{@"default":@{@"zdy":@[@40,@200,@90],
                                                                                                @"yjk":@[@40,@200,@90],
                                                                                                @"fc":@[@40,@200,@90],
                                                                                                @"hz":@[@40,@200,@90]},
                                                                                   @"set":@{@"zdy":@[],
                                                                                            @"yjk":@[],
                                                                                            @"fc":@[],
                                                                                            @"hz":@[]}}];
       BOOL bol = [dic writeToFile:path atomically:YES];
        if (!bol) {
            JLLog(@"写入失败");
        }
    }
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:UserCallMeTypeSos] == nil) {
        NSString *userid = [JlUserManager shareInstance].userInfo.userid;
        JLCallMeModel *sosModel = [[JLCallMeModel alloc] initWithTime:@"1" Type:@"1" userId:userid];
        [NSUserDefaults setUserObject:sosModel forKey:UserCallMeTypeSos];
        
        JLCallMeModel *earlyWarning = [[JLCallMeModel alloc] initWithTime:@"1" Type:@"2" userId:userid];
        [NSUserDefaults setUserObject:earlyWarning forKey:UserCallMeTypeEarlyWarning];
        
        JLCallMeModel *alarm = [[JLCallMeModel alloc]initWithTime:@"1" Type:@"3" userId:userid];
        [NSUserDefaults setUserObject:alarm forKey:UserCallMeTypeAlarm];
        
        JLCallMeModel *fallDown = [[JLCallMeModel alloc]initWithTime:@"1" Type:@"4" userId:userid];
        [NSUserDefaults setUserObject:fallDown forKey:UserCallMeTypeFallDown];
    }
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:UserHealthSelete] == nil) {
        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:UserHealthSelete];
    }
}

+ (void)backgroundLogin {
    NSString *passWord = [[NSUserDefaults standardUserDefaults] objectForKey:UserDataPassWord];
    [InterfaceNetManager RequestLogin:[JlUserManager shareInstance].userInfo.userid
                             PassWord:passWord
                           completion:^(BOOL isSucceed,
                                                                                          NSString *message,
                                                                                          id data,
                                                                                          NSError *error) {
        if (isSucceed) {
            UserInfoModel *model = [UserInfoModel objectWithKeyValues:data];
            [NSUserDefaults  setUserObject:model
                                    forKey:UserInfoUserDefault];
            [NSUserDefaults setObject:passWord
                               forKey:UserDataPassWord];
        }
    }];

}

+ (void)chooseRootViewController {
    JlUserManager *userManager = [JlUserManager shareInstance];
    NSString *passWord = [[NSUserDefaults standardUserDefaults] objectForKey:UserDataPassWord];
    NSNumber *FirstRun = [[NSUserDefaults standardUserDefaults] objectForKey:JiuLeFirstRun];
//    NSNumber *New = [[NSUserDefaults standardUserDefaults] objectForKey:JiuLeNewFeatures];
    // || (New == nil || [New isKindOfClass:[NSNull class]] || [New boolValue])
    if ((FirstRun == nil || [FirstRun isKindOfClass:[NSNull class]] || [FirstRun boolValue])) {
        //TODO去引导页
        JLContentViewController *jl = [[JLContentViewController alloc] init];
        [UIApplication sharedApplication].delegate.window.rootViewController = jl;
        return;
    }
    if ((userManager.userInfo.userid != nil && ![userManager.userInfo.userid isEqualToString:@""]) && (passWord != nil && ![passWord isEqualToString:@""])) {
        [AppDelegate backgroundLogin];
        [AppDelegate goHomePage];
    } else {
        //进入登陆页面
        LoginViewController *login = getStoryOfControllerInstance(@"LoginViewController");
        [UIApplication sharedApplication].delegate.window.rootViewController = login;
    }
}

+ (void)goHomePage {
    JlUserManager *userManager = [JlUserManager shareInstance];
    //跳转首页
    CYLTabBarController *tabbar = [[CYLTabBarController alloc] init];
    [self setUpTabBar:tabbar];
    userManager.baseTab = tabbar;
    SideMenuContentViewController *personal  = getStoryOfControllerInstance(@"SideMenuContentViewController");
    BaseNavController *base = [[BaseNavController alloc] initWithRootViewController:personal];
    personal.navigationController.navigationBarHidden = YES;
    RESideMenu *sideMenu              = [[RESideMenu alloc] init];
    sideMenu.leftMenuViewController   = base;
    sideMenu.contentViewController    = tabbar;
    sideMenu.menuPreferredStatusBarStyle = UIStatusBarStyleLightContent;
    sideMenu.backgroundImage       = [UIImage imageNamed:@"bg"];
    sideMenu.contentViewShadowColor   = [UIColor blackColor];
    sideMenu.contentViewShadowOffset  = CGSizeMake(0, 0);
    sideMenu.contentViewShadowOpacity = 0.6;
    sideMenu.contentViewShadowRadius  = 12;
    sideMenu.contentViewShadowEnabled = YES;
    sideMenu.interactivePopGestureRecognizerEnabled = YES;
    sideMenu.contentViewScaleValue = 0.9;
    sideMenu.panGestureEnabled        = YES;
    sideMenu.panFromEdge              = NO;
    userManager.menu = sideMenu;
    [UIApplication sharedApplication].delegate.window.rootViewController    = sideMenu;
    userManager.menu                         = sideMenu;
}

+ (void)setUpTabBar:(CYLTabBarController *)_tabBarController {
    
    HomePageViewController *home = getStoryOfControllerInstance(@"HomePageViewController");
    BaseNavController *baseNav1 = [[BaseNavController alloc] initWithRootViewController:home];
    
    MallViewController *mall = getStoryOfControllerInstance(@"MallViewController");
   
    ServiceViewController *service = getStoryOfControllerInstance(@"ServiceViewController");
    BaseNavController *baseNav3 = [[BaseNavController alloc] initWithRootViewController:service];
    
    MessageViewController *message = getStoryOfControllerInstance(@"MessageViewController");
    BaseNavController *baseNav4 = [[BaseNavController alloc] initWithRootViewController:message];
    
    MyZoneViewController *myZone = getStoryOfControllerInstance(@"MyZoneViewController");
    
    [AppDelegate customizeTabBarForController:_tabBarController];
    
    // set the text color for unselected state
    // 普通状态下的文字属性
    NSMutableDictionary *normalAttrs = [NSMutableDictionary dictionary];
    normalAttrs[NSForegroundColorAttributeName] = [UIColor blackColor];
    normalAttrs[NSFontAttributeName] = [UIFont fontWithName:kfontName size:14.];
    
    // set the text color for selected state
    // 选中状态下的文字属性
    NSMutableDictionary *selectedAttrs = [NSMutableDictionary dictionary];
    selectedAttrs[NSForegroundColorAttributeName] = [UIColor colorWithHex:0x217AB9];
    selectedAttrs[NSFontAttributeName] = [UIFont fontWithName:kfontName size:14.];
    // set the text Attributes
    // 设置文字属性
    UITabBarItem *tabBar = [UITabBarItem appearance];
    [tabBar setTitleTextAttributes:normalAttrs forState:UIControlStateNormal];
    [tabBar setTitleTextAttributes:selectedAttrs forState:UIControlStateSelected];
    
    [_tabBarController setViewControllers:@[
                                           baseNav1,
                                           baseNav4,
                                           baseNav3,
                                           mall,
                                           myZone,
                                           ]];
    
}

+ (void)customizeTabBarForController:(CYLTabBarController *)tabBarController {
    
    NSDictionary *dict1 = @{
                            CYLTabBarItemTitle : @"首页",
                            CYLTabBarItemImage : @"nav_home",
                            CYLTabBarItemSelectedImage : @"nav_home_cur",
                            };
    NSDictionary *dict2 = @{
                            CYLTabBarItemTitle : @"商城",
                            CYLTabBarItemImage : @"nav_shop",
                            CYLTabBarItemSelectedImage : @"shop_selete",
                            };
    NSDictionary *dict3 = @{
                            CYLTabBarItemTitle : @"服务",
                            CYLTabBarItemImage : @"nav_service",
                            CYLTabBarItemSelectedImage : @"ser2_ico",
                            };
    NSDictionary *dict4 = @{
                            CYLTabBarItemTitle : @"消息",
                            CYLTabBarItemImage : @"nav_mail",
                            CYLTabBarItemSelectedImage : @"mail2_ico(1)"
                            };
    NSDictionary *dict5 = @{
                            CYLTabBarItemTitle : @"我的",
                            CYLTabBarItemImage : @"nav_me",
                            CYLTabBarItemSelectedImage : @"me2_ico"
                            };
    NSArray *tabBarItemsAttributes = @[
                                       dict1,
                                       dict4,
                                       dict3,
                                       dict2,
                                       dict5
                                       ];
    tabBarController.tabBarItemsAttributes = tabBarItemsAttributes;
  
    UIColor *titleHighlightedColor = [UIColor darkGrayColor];
    [[UITabBarItem appearance] setTitleTextAttributes:
     [NSDictionary dictionaryWithObjectsAndKeys: titleHighlightedColor, NSForegroundColorAttributeName,iOS8Font(16.f), NSFontAttributeName, nil] forState:UIControlStateSelected];
    UIImage *tabbarimage=[UIImage imageNamed:@"nav_bg"];
    UIImageView *tabBarBackgroundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0,
                                                                                           tabBarController.tabBar.frame.size.width, tabBarController.tabBar.frame.size.height)];
    //tabBarBackgroundImageView.contentMode = UIViewContentModeScaleAspectFit;//效果将按原图原来的比例缩放
    tabBarBackgroundImageView.image =tabbarimage;
    [tabBarController.tabBar insertSubview:tabBarBackgroundImageView atIndex:1];
}

/** 注册用户通知 */
- (void)registerUserNotification {
    /*
     注册通知(推送)
     申请App需要接受来自服务商提供推送消息
     */
    // 判读系统版本是否是“iOS 8.0”以上
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 ||
        [UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]) {
        
        // 定义用户通知类型(Remote.远程 - Badge.标记 Alert.提示 Sound.声音)
        UIUserNotificationType types = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
        // 定义用户通知设置
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        
        // 注册用户通知 - 根据用户通知设置
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    
    } else {      // iOS8.0 以前远程推送设置方式
        // 定义远程通知类型(Remote.远程 - Badge.标记 Alert.提示 Sound.声音)
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
        
        // 注册远程通知 -根据远程通知类型
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
    }
}

/** 自定义：APP被“推送”启动时处理推送消息处理（APP 未启动--》启动）*/
- (void)receiveNotificationByLaunchingOptions:(NSDictionary *)launchOptions {
    JLLog(@"--------------------------- 推送在处理 ----------------------------");
    [self pushMessage];
}

- (void)pushMessage {
    if (!isBackGround) {
        UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"提示" message:@"您有一条新消息。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"立即查看", nil];
        alert.delegate = self;
        alert.tag = 0x25;
        [alert show];
    } else {
        isBackGround = NO;
        [self pushLogicalHandle];
    }
}

- (void)pushLogicalHandle {
    JlUserManager *userManager = [JlUserManager shareInstance];
    if ([userManager.menu.contentViewController isKindOfClass:[CYLTabBarController class]]) {
        if (userManager.baseTab.selectedIndex == 1 ) {
            BaseNavController *base = userManager.baseTab.selectedViewController;
            if (base.viewControllers.count > 1) {
                [base popViewControllerAnimated:NO];
            }
//            postNotification(HomePagePostMessageReloadWithType);
            postNotificationWithObject(HomePagePostMessageReloadWithType, @"");
        } else {
            userManager.baseTab.selectedIndex = 1;
        }
    } else {
        [userManager.menu setContentViewController:userManager.baseTab];
        [userManager.menu hideMenuViewController];
        userManager.baseTab.selectedIndex = 1;
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 0x25 && buttonIndex == 1) {
        [self pushLogicalHandle];
    } else {
        postNotification(@"refreshHome");
    }
}

#pragma mark - 用户通知(推送)回调 _IOS 8.0以上使用

/** 已登记用户通知 */
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
    // 注册远程通知（推送）
    [application registerForRemoteNotifications];
}

- (void)GeTuiSdkDidReceivePayload:(NSString *)payloadId andTaskId:(NSString *)taskId andMessageId:(NSString *)aMsgId andOffLine:(BOOL)offLine fromApplication:(NSString *)appId {
    // [4]: 收到个推消息
    JLLog(@"--------------------------- 透传回调 推送来啦 ----------------------------");
    NSData* payload = [GeTuiSdk retrivePayloadById:payloadId];
    if (payload) {
        [self pushMessage];
    }
    
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
    JLLog(@"--------------------------- 推送来啦 ----------------------------");
    if (((HomePageViewController *)((BaseNavController *)[[JlUserManager shareInstance].baseTab.viewControllers firstObject]).topViewController).model == nil) {
        return;
    }
    [self receiveNotificationByLaunchingOptions:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

/** SDK启动成功返回cid */
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
    // [4-EXT-1]: 个推SDK已注册，返回clientId
    NSLog(@"\n>>>[GeTuiSdk RegisterClient]:%@\n\n", clientId);
  
    [GeTuiSdk runBackgroundEnable:YES];
    [GeTuiSdk setPushModeForOff:NO];
    if ([JlUserManager shareInstance].userInfo.userid == nil || [[JlUserManager shareInstance].userInfo.userid isEqualToString:@""]) {
        [[NSUserDefaults standardUserDefaults] setObject:@(NO) forKey:@"push"];
        return;
    }
    [GeTuiSdk bindAlias:[JlUserManager shareInstance].userInfo.userid];
    [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:@"push"];
}

/** SDK遇到错误回调 */
- (void)GeTuiSdkDidOccurError:(NSError *)error {
    // [EXT]:个推错误报告，集成步骤发生的任何错误都在这里通知，如果集成后，无法正常收到消息，查看这里的通知。
    NSLog(@"\n>>>[GexinSdk error]:%@\n\n", [error localizedDescription]);
}

/** 远程通知注册成功委托 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    _myToken = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    _myToken = [_myToken stringByReplacingOccurrencesOfString:@" " withString:@""];
      [GeTuiSdk registerDeviceToken:_myToken];    /// 向个推服务器注册deviceToken
    NSLog(@"\n>>>[DeviceToken Success]:%@\n\n",_myToken);
}

/** 远程通知注册失败委托 */
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    [GeTuiSdk registerDeviceToken:@""];     /// 如果APNS注册失败，通知个推服务器
    NSLog(@"\n>>>[DeviceToken Error]:%@\n\n",error.description);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [self receiveNotificationByLaunchingOptions:userInfo];
}

- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    /// Background Fetch 恢复SDK 运行
    [GeTuiSdk resume];
    completionHandler(UIBackgroundFetchResultNewData);
}


- (void)applicationWillResignActive:(UIApplication *)application {
    JLLog(@"app status : %zd , %s",[UIApplication sharedApplication].applicationState , __FUNCTION__);
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    isBackGround = YES;
    JLLog(@"app status : %zd , %s",[UIApplication sharedApplication].applicationState , __FUNCTION__);
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    JLLog(@"app status : %zd , %s",[UIApplication sharedApplication].applicationState , __FUNCTION__);

    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    isBackGround = NO;
    [CLUIBaseViewController connectWifi];
    JLLog(@"app status : %zd , %s",[UIApplication sharedApplication].applicationState , __FUNCTION__);
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    JLLog(@"app status : %zd , %s",[UIApplication sharedApplication].applicationState , __FUNCTION__);

    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
